﻿using System;
using System.Web;
using GNSCore.Model;

namespace GNSCore.Helpers
{
    /// <summary>
    /// For managing entity context life time
    /// </summary>
    public class ContextHelper : IDisposable
    {
        private static ContextHelper _ctxHelper;

        public ContextHelper()
        {
            HttpContext.Current.Items["context"] = new GNSDBEntities();
        }

        /// <summary>
        /// 'Singleton' pattern. Property returns single ContextManager instance
        /// </summary>
        public static ContextHelper Instance
        {
            get
            {
                if (_ctxHelper == null)
                {
                    _ctxHelper = new ContextHelper();
                }
                return _ctxHelper;
            }
        }

        public GNSDBEntities Context
        {
            get
            {
                if (HttpContext.Current.Items["context"] == null)
                {
                    return new ContextHelper().Context;
                }

                return (GNSDBEntities) HttpContext.Current.Items["context"];
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (HttpContext.Current.Items["context"] != null)
            {
                var ctx = (GNSDBEntities) HttpContext.Current.Items["context"];
                ctx.Dispose();
            }
        }

        #endregion
    }
}